﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace Brick
{
    public class OpenPreferencesWindow : EditorWindow
    {
        [MenuItem("Tool/OpenPreferencesWindow")]
        public static void Open()
        {
            OpenPreferencesWindow editor = EditorWindow.GetWindow<OpenPreferencesWindow>();
        }

        private void OnGUI()
        {
            if (GUILayout.Button("打开 PerferencesWindow"))
            {
                Assembly assembly = Assembly.GetAssembly(typeof(UnityEditor.EditorWindow));
                Type type = assembly.GetType("UnityEditor.PreferencesWindow");
                type.GetMethod("ShowPreferencesWindow", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);
            }
        }

        // 拷贝Project视图中的某个Prefab
        private void ProjectDuplicate()
        {
            var type = typeof(Editor).Assembly.GetType("UnityEditor.ProjectWindowUtil");

            var duplicate = type.GetMethod("DuplicateSelectedAssets",
                System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);

            duplicate.Invoke(null, null);
        }

        // 拷贝Hierarchy视图中的某个Prefab，优点：（1）速度快（2）保持引用关系。在代码中Instantiate会丢失引用，并且速度很慢
        private void HierarchyDuplicate()
        {
            var type = typeof(Editor).Assembly.GetType("UnityEditor.SceneHierarchyWindow");
            var window = EditorWindow.GetWindow(type);
            var duplicateSelectedFunc = type.GetMethod("DuplicateGO",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);

            duplicateSelectedFunc.Invoke(window, null);
        }

        // 手动设置Game视图的分辨率，可以用来在编辑态下动态改变runtime分辨率
        public static void SetGameView(int index)
        {
            var type = typeof(Editor).Assembly.GetType("UnityEditor.GameView");
            var window = EditorWindow.GetWindow(type);
            var SizeSelectionCallback = type.GetMethod("SizeSelectionCallback",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            SizeSelectionCallback.Invoke(window, new object[] { index, null });
        }
    }
}

